package com.tupu.controller.dispatch;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tupu.common.Result;
import com.tupu.common.StatusCode;
import com.tupu.entity.dispatch.*;
import com.tupu.service.admin.PerformMsgService;
import com.tupu.service.dispatch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;

/**
 * 调度日志
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/dispatch")
public class DispatchController {

    @Autowired(required = false)
    private OverhaulPlanService overhaulPlanService;

    @Autowired(required = false)
    private OperTicketService operTicketService;

    @Autowired(required = false)
    private OperTicketDetailsService operTicketDetailsService;

    @Autowired(required = false)
    private PerformMsgService performMsgService;

    @Resource
    private DadsDdrzService dacsDdrzService;

    /**
     * 调度日志-计划票-维修计划-检修计划-列表条件搜索、分页
     *
     * @param page
     * @param size
     * @param station_name
     * @param start_time
     * @param end_time
     * @param work_content
     * @param interval_name
     * @return
     */
    @PostMapping("/overhaulPlanList")
    public Result OverhaulPlanList(@RequestParam(required = false, defaultValue = "1") Long page,
                                   @RequestParam(required = false, defaultValue = "10") Long size,
                                   @RequestParam(required = false) String station_name,//厂站
                                   @RequestParam(required = false) String start_time,//开始时间
                                   @RequestParam(required = false) String end_time,//结束时间
                                   @RequestParam(required = false) String work_content,//工作内容
                                   @RequestParam(required = false) String interval_name//工作内容
    ) {
        Page<DispatchPlannedOverhaulPlan> pageInfo = null;
        try {
            pageInfo = overhaulPlanService.conditionSearch(page, size, station_name, start_time, end_time, work_content, interval_name);
            List<DispatchPlannedOverhaulPlan> dispatchPlannedOverhaulPlans = pageInfo.getRecords();
            for (DispatchPlannedOverhaulPlan dispatchPlannedOverhaulPlan : dispatchPlannedOverhaulPlans) {
                if (ObjectUtil.isNotEmpty(dispatchPlannedOverhaulPlan.getPlanStartTime()) && ObjectUtil.isNotEmpty(dispatchPlannedOverhaulPlan.getPlanEndTime())) {
                    String kssj = DateUtil.formatDateTime(dispatchPlannedOverhaulPlan.getPlanStartTime());
                    String jssj = DateUtil.formatDateTime(dispatchPlannedOverhaulPlan.getPlanEndTime());
                    dispatchPlannedOverhaulPlan.setPlanTime(kssj + "-" + jssj);
                }
            }
            return Result.ok(pageInfo);
        } catch (ParseException e) {
            log.error("检修计划列表错误，错误信息" + e.getMessage());
            return Result.ok(pageInfo);
        }
    }

    /**
     * 调度日志-计划票-维修计划-检修计划-查询间隔时间
     *
     * @return
     * @throws ParseException
     */
    @PostMapping("/intervalTime")
    public Result intervalTime() throws ParseException {
        List<String> timeList = overhaulPlanService.intervalTime();
        return Result.ok(timeList);
    }

    /**
     * 展示所有厂站
     *
     * @return
     */
    @PostMapping("/stationList")
    public Result findAllStation() {
        List<String> list = overhaulPlanService.findAllStation();
        return Result.ok(list);
    }

    /**
     * 根据场站展示间隔
     *
     * @return
     */
    @PostMapping("/intervalList")
    public Result findIntervalByStationName(@RequestParam String station_name) {
        List<String> list = overhaulPlanService.findIntervalByStationName(station_name);
        return Result.ok(list);
    }

    /**
     * 根据检修计划表id查询推荐的操作票
     *
     * @param page
     * @param size
     * @param station_name
     * @return
     */
    @PostMapping("/ticketList")
    public Result operTicketList(@RequestParam(required = false, defaultValue = "1") Long page,
                                 @RequestParam(required = false, defaultValue = "10") Long size,
                                 @RequestParam(required = false) String station_name // 场站名称
    ) {
        Page<DispatchPlannedOperTicket> pageInfo = null;
        try {
            pageInfo = operTicketService.findAll(page, size, station_name);
            return Result.ok(pageInfo);
        } catch (Exception e) {
            return Result.ok(pageInfo);
        }
    }

    /**
     * 根据操作票id 查询详情
     *
     * @param ticket_id
     * @return
     */
    @PostMapping("/detailsList")
    public Result operTicketDetailsList(@RequestParam(required = false) String ticket_id) {
        DispatchOperTicketDetails details;
        try {
            details = operTicketDetailsService.findAll(ticket_id);
            return Result.ok(details);
        } catch (Exception e) {
            return Result.ok(e.getMessage());
        }
    }

    /**
     * 保存或更新操作票信息
     *
     * @param details
     * @return
     */
    @PostMapping("/saveOperTicketDetails")
    public Result operTicketDetails(@Validated @RequestBody DispatchOperTicketDetails details, BindingResult result) {
        try {
            if (result.hasErrors()) {
                StringBuilder sb = new StringBuilder();
                for (ObjectError error : result.getAllErrors()) {
                    sb.append(error.getDefaultMessage() + ";");
                }
                return Result.error(sb.toString());
            }
            return Result.ok(operTicketDetailsService.saveOperTicketDetailsList(details));
        } catch (Exception e) {
            return Result.ok(e.getMessage());
        }
    }

    /**
     * 添加执行信息
     *
     * @param msg
     * @return
     */
    @PostMapping("/addMsg")
    public Result addMsg(@RequestBody(required = false) DispatchOperTicketPerformMsg msg) {
        try {
            performMsgService.addMsg(msg);
            return Result.ok("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(StatusCode.PARAM_ERROR);
        }
    }

    /**
     * 删除一条执行信息
     *
     * @param msg_id
     * @return
     */
    @PostMapping("/delDetail")
    public Result delTicketDetails(String msg_id) {
        try {
            performMsgService.delMsg(msg_id);
            return Result.ok("删除成功");
        } catch (Exception e) {
            return Result.error(StatusCode.PARAM_ERROR);
        }
    }

    /**
     * 根据执行信息id 选一条数据
     *
     * @param msg_id
     * @return
     */
    @PostMapping("/findOneDetail")
    public Result findOneDetailById(String msg_id) {
        if (null != msg_id) {
            DispatchOperTicketPerformMsg msg = performMsgService.findById(msg_id);
            return Result.ok(msg);
        }
        return Result.error(StatusCode.PARAM_ERROR);
    }

    /**
     * 上移
     *
     * @param msg_id
     * @return
     */
    @PostMapping("/moveUp")
    public Result moveUp(String msg_id) {
        if (null != msg_id) {
            Integer result = performMsgService.moveUp(msg_id);
            if (result.equals(0)) {
                return Result.errorMessage("已是第一条数据,无法上移");
            }
            return Result.ok("上移成功");
        }
        return Result.error(StatusCode.PARAM_ERROR);
    }

    /**
     * 下移
     *
     * @param msg_id
     * @return
     */
    @PostMapping("/moveDown")
    public Result moveDown(String msg_id) {
        if (null != msg_id) {
            Integer result = performMsgService.moveDown(msg_id);
            if (result.equals(0)) {
                return Result.errorMessage("已是最后一条数据,无法下移");
            }
            return Result.ok("下移成功");
        }
        return Result.error(StatusCode.PARAM_ERROR);
    }

    @RequestMapping(value = "/queryVDacsDdrzPage", name = "查询调度日志列表")
    public Result queryVDacsDdrzPage(@RequestBody QueryDdrzParmas params) {
        try {
            return Result.ok(dacsDdrzService.queryVDacsDdrzPage(params, params.getPage(), params.getSize()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询调度日志错误！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/queryHistoryJxd", name = "根据设备名称查询检修信息")
    public Result queryHistoryJxd(@RequestBody QueryDdrzParmas parmas) {
        try {
            return Result.ok(dacsDdrzService.queryHistoryJxd(parmas));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询检修单信息失败！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/queryDadsJxdById", name = "根据检修单ID查询检修单信息")
    public Result queryDadsJxdById(@RequestParam String listId) {
        try {
            return Result.ok(dacsDdrzService.queryDadsJxdById(listId));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询检修单信息失败！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/queryHistoryBgd", name = "根据设备名称查询变更单列表")
    public Result qeuryHistoryBgd(@RequestBody QueryDdrzParmas parmas) {
        try {
            return Result.ok(dacsDdrzService.queryHistoryBgd(parmas));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询检修单信息失败！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/queryDadsFsdgdById", name = "根据变更单ID查询变更单信息")
    public Result queryDadsFsdgdById(@RequestParam String listId) {
        try {
            return Result.ok(dacsDdrzService.queryDadsFsdgdById(listId));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询检修单信息失败！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/memoMsgList", name = "根据日期查询值班操作备忘信息")
    public Result queryDadsZbczbwxx(@RequestParam String dutyDate,
                                    @RequestParam(required = false, defaultValue = "1") String type,
                                    @RequestParam(required = false) String sbmc,
                                    @RequestParam(required = false) String czmc,
                                    @RequestParam(required = false) String allCheck) {
        try {
            return Result.ok(dacsDdrzService.queryDadsZbczbwxx(dutyDate, type, sbmc, czmc, allCheck));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询值班操作备忘信息！" + e.getMessage());
        }
    }

    @RequestMapping(value = "/insertOrUpdateJxczbwl", name = "保存检修操作备忘录信息")
    public Result insertOrUpdateJxczbwl(@RequestBody DadsJxczbwl dadsJxczbwl) {
        try {
            return Result.ok(dacsDdrzService.insertOrUpdateJxczbwl(dadsJxczbwl));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存检修操作备忘录信息失败！" + e.getMessage());
        }
    }

    @PostMapping(value = "/TestOverhaulPlanList", name = "定时任务查询处理计划操作票")
    public Result TestOverhaulPlanList() {
        log.info("计划操作票分析");
        overhaulPlanService.analysisJHCZP();
        log.info("计划操作票分析完成");
        return Result.ok("计划操作票分析完成");
    }
}